import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;

import static java.net.URLDecoder.decode;

public class YuQuePage {

    private static Path homePath = Path.of(System.getProperty("user.dir"), "src/main/resources/yuque");
    private static String cssTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\">";
    private static String jsTag = "<script src=\"./script.js\">";
    private static String metaTag = "<meta charset=\"UTF-8\">";

    public static void main(String[] args) {
        try {
            createPage();
            restoreDocs();
            System.out.println("finished.");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 替换文件内容，加上后缀 .html
    private static void restoreDocs() throws IOException {
        Path docsPath = Path.of(homePath+ "/docs");
        File files = docsPath.toFile();
        ObjectMapper mapper = new ObjectMapper();
        for (File file : files.listFiles((dir, name) -> !name.endsWith(".html"))) {
            Document doc = Document.createShell("");
            doc.outputSettings().prettyPrint(true);
            JsonNode data = mapper.readTree(file);
            doc.body().append(data.get("data").get("content").asText());
            doc.getElementsByTag("meta").remove();
            doc.head().append(metaTag);
            Elements es = doc.getElementsByTag("card");
            for (Element e : es) {
                Attributes att = e.attributes();
                JsonNode tagData = mapper.readTree(decode(att.get("value"), "UTF-8").replace("data:", ""));
                // 代码片段
                if (att.get("name").equals("codeblock")) {
                    e.after("<pre lang=\"java\"><code>\n" + HtmlUtils.htmlEscape(tagData.get("code").asText()) + "\n</code></pre>");
                }
                // image
                else if (att.get("name").equals("image")) {
                    e.after("<img src=" + tagData.get("src") + ">");
                }
                e.remove();
            }
            Path path = docsPath.resolve(file.getName() + ".html");
            System.out.println(path);
            Files.write(path, doc.html().getBytes());
        }
    }

    private static void createPage() throws Exception {

        Document document = Document.createShell("");
        document.outputSettings().prettyPrint(true);
        document.head().append(cssTag);
        document.head().append(jsTag);
        document.head().append(metaTag);
        Element div = document.body().appendElement("div").appendElement("div");
        div.addClass("menu");
        ObjectMapper mapper = new ObjectMapper();
        String docsPath = "./docs/";
        JsonNode menu = mapper.readTree(new File(homePath +  "/data/menu.json"));
        Iterator<JsonNode> it = menu.get("data").elements();
        while (it.hasNext()) {
            JsonNode e = it.next();
            String type = e.get("type").asText();
            String title = e.get("title").asText();
            if ("DOC".equals(type)) {
                Element element = div.getElementById(e.get("parent_uuid").asText());
                String href = docsPath + e.get("url").asText() + ".html";
                element.append("<li><a href='" + href + "' onclick=\"fetchHtml(this);\">" +title+ "</a></li>");
            }
            else {
                div.append("<ul id=" +e.get("uuid").asText()+ ">" +title+ "</ul>");
            }
        }
        div.after("<div id=\"content\"></div>");
        // 将文档内容写入磁盘
        Files.write(homePath.resolve("index.html"), document.html().getBytes());
    }
}
